package com.bootdo.ocr.baidu;

import com.alibaba.fastjson.JSON;
import com.baidu.aip.ocr.AipOcr;
import com.bootdo.ocr.*;
import com.bootdo.ocr.baidu.dto.BaiduOcrResult;
import com.bootdo.ocr.xfyun.dto.XfYunOcrResult;
import com.bootdo.utils.PDFToIMGUtil;
import com.google.common.collect.Lists;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaiDuOcrService extends OcrService<BaiduOcrResult> {

    AipOcr client = null;

    public BaiDuOcrService(String apiKey, String secretKey, String appId) {
        init(apiKey, secretKey, appId);
    }

    /**
     * 初始化参数
     * @param apiKey
     * @param secretKey
     * @param appId
     */
    @Override
    protected void init(String apiKey, String secretKey, String appId) {
        this.apiKey = apiKey;
        this.appId = appId;
        this.secretKey = secretKey;
        client = new AipOcr(appId, apiKey, secretKey);
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
    }

    @Override
    protected List<BaiduOcrResult> fetchOcrDataByFileUrlDTO(FileUrlDTO dto) {
        final Map<String, String> filePathMap = dto.getFilePathMap();
        List<BaiduOcrResult> results = Lists.newLinkedList();
        Map<String, BaiduOcrResult> resultMap = new HashMap<>();
        for (String sourcePath : filePathMap.keySet()) {
            // 调用接口
            String path = filePathMap.get(sourcePath);
            JSONObject res = null;
            try {
                res = client.basicGeneral(path, new HashMap<String, String>());
                final String[] split = path.split("\\\\");
                final BaiduOcrResult baiDuOcrResult = tranJsonBean(res.toString(2), BaiduOcrResult.class);
                final String fileName = split[split.length - 1].replace(".png", "");
                baiDuOcrResult.setFileName(fileName);
                baiDuOcrResult.setFilePath(sourcePath);
                resultMap.put(sourcePath, baiDuOcrResult);
                if(validateDoRepeat(baiDuOcrResult)) {
                    dto.getFailFilePathMap().put(sourcePath, filePathMap.get(sourcePath));
                }
            } catch (Exception e) {
                logger.error("baidu fetchOcrDataByFileUrlDTO decode error ====== >>>>>>" + res.toString(2), e);
                dto.getFailFilePathMap().put(sourcePath, filePathMap.get(sourcePath));
            }
        }
        roundRobinApi(dto, 1, resultMap);
        results.addAll(resultMap.values());
        logger.info("cover data " + JSON.toJSONString(results));
        results.forEach(obj -> obj.matchCode(dto.getPattern()));
        return results;
    }

    /**
     * 校验是否重新处理
     * @param baiduOcrResult 处理结果
     * @return boolean
     */
    @Override
    protected boolean validateDoRepeat(BaiduOcrResult baiduOcrResult) {
        if(baiduOcrResult.getWordsResultNum() == 0) {
            return true;
        }
        return false;
    }

    /**
     * 递归5次 调用还是失败就不管了
     * @param dto
     * @param pollIndex
     * @param resultMap
     */
    @Override
    protected void roundRobinApi(FileUrlDTO dto, int pollIndex,  Map<String, BaiduOcrResult> resultMap) {

        final Map<String, String> failFilePathMap = dto.getFailFilePathMap();

        if (failFilePathMap.size() > 0) {
            for (String sourcePath : failFilePathMap.keySet()) {
                // 转化成 png
                JSONObject res = null;
               try {
                   PDFToIMGUtil.pdf2PngPath(sourcePath, failFilePathMap.get(sourcePath), DPIVAL_MAP.get(pollIndex));
                   String path = failFilePathMap.get(sourcePath);
                   res = client.basicGeneral(path, new HashMap<String, String>());
                   final String[] split = path.split("\\\\");
                   final BaiduOcrResult baiDuOcrResult = tranJsonBean(res.toString(2), BaiduOcrResult.class);
                   final String fileName = split[split.length - 1].replace(".png", "");
                   baiDuOcrResult.setFileName(fileName);
                   baiDuOcrResult.setFilePath(sourcePath);
                   resultMap.put(sourcePath, baiDuOcrResult);

                   if(validateDoRepeat(baiDuOcrResult)) {
                       dto.getFailFilePathMap().put(sourcePath, path);
                   } else {
                       failFilePathMap.remove(sourcePath);
                   }
               } catch (Exception e) {
                   logger.error("baidu pollApi decode error ====== >>>>>>" + res.toString(2), e);
               }

            }
        }
        pollIndex ++;
        if (pollIndex <= POLL_TIME  && dto.getFailFilePathMap().size() > 0) {
            roundRobinApi(dto, pollIndex, resultMap);
        }
    }
}
